package br.com.honorato.ejb;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionManagement;
import javax.ejb.TransactionManagementType;
import javax.faces.bean.ManagedProperty;
import javax.interceptor.Interceptors;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;

import br.com.honorato.bean.AppScopedBean;
import br.com.honorato.dao.RuleDAO;
import br.com.honorato.exception.EJBServiceException;
import br.com.honorato.logger.Depurador;
import br.com.honorato.logger.InterceptorDeCallback;
import br.com.honorato.logger.LoggerInterceptor;
import br.com.honorato.model.Rule;
import br.com.honorato.model.UserApp;
import br.com.honorato.util.FacesUtil;

/**
 * Session Bean implementation class LoginEJB
 */
@SuppressWarnings("deprecation")
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
@Interceptors(
{ Depurador.class, InterceptorDeCallback.class })
public class AuthenticationEJB extends BaseEJB
{

	@ManagedProperty(value = "#{appScopedBean}")
	private AppScopedBean appScopedBean;

	@EJB
	UserEJB userEjb;

	public AuthenticationEJB()
	{}

	@LoggerInterceptor
	public User authenticateUser(String login) throws EJBServiceException
	{
		UserApp userApp = null;

		userApp = userEjb.getUserByLogin(login);

		if (userApp == null)
		{
			return null;
		}

		List<Rule> ruleList = null;

		if (login.equalsIgnoreCase(FacesUtil.getLoginAdminDefault()))
		{ // Atribui
			// todas
			// as
			// Rules
			// ao
			// usu�rio
			// administrador
			ruleList = new RuleDAO(getEm()).selectAll();
		}
		else
		{ // TODO: recuperar somente RULES do referido usuario
			ruleList = new RuleDAO(getEm()).selectAll();
		}

		List<GrantedAuthority> userGrantedAuthorityList = new ArrayList<GrantedAuthority>();

		for (Rule rule : ruleList)
		{
			userGrantedAuthorityList.add(new GrantedAuthorityImpl(rule.getCodeRule()));
		}

		org.springframework.security.core.userdetails.User userOut = new org.springframework.security.core.userdetails.User(userApp.getLogin(),
				userApp.getPassword(), true, true, true, true, userGrantedAuthorityList);

		return userOut;
	}
}